package com.byq.ai.agentlab.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;

@Service
public class EmbeddingService {
    @Value("${openai.api.key}")
    private String apiKey;

    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();
    private static final String OPENAI_API_URL = "https://api.deepseek.com/v3/embeddings";

    public float[] generateEmbedding(String text) {
        try {
            String requestBody = String.format(
                "{\"model\": \"text-embedding-ada-002\", \"input\": \"%s\"}",
                text.replace("\"", "\\\"")
            );

            String response = restTemplate.postForObject(
                OPENAI_API_URL,
                requestBody,
                String.class
            );

            JsonNode root = objectMapper.readTree(response);
            JsonNode embedding = root.get("data").get(0).get("embedding");
            
            float[] result = new float[1536];
            for (int i = 0; i < 1536; i++) {
                result[i] = (float) embedding.get(i).asDouble();
            }
            
            return result;
        } catch (Exception e) {
            throw new RuntimeException("Failed to generate embedding", e);
        }
    }
} 